<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <style>
        /* 全局样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Microsoft YaHei', sans-serif;
        }
        
        body {
            background-color: #f5f5f5;
            color: #333;
        }
        
        /* 页面容器 */
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        /* 页面标题 */
        .page-title {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #333;
        }
        
        /* 内容区域 */
        .content-area {
            background-color: #fff;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        /* 搜索筛选区域 */
        .search-filter {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .search-input {
            flex: 1;
            min-width: 200px;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-right: 10px;
        }
        
        .filter-select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-right: 10px;
        }
        
        .search-btn {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        
        .search-btn:hover {
            background-color: #45a049;
        }
        
        .add-btn {
            padding: 8px 16px;
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .add-btn:hover {
            background-color: #1976D2;
        }
        
        /* 表格样式 */
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        
        .data-table th,
        .data-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        .data-table th {
            background-color: #f8f9fa;
            font-weight: bold;
            color: #666;
        }
        
        .data-table tr:hover {
            background-color: #f5f5f5;
        }
        
        /* 操作按钮 */
        .action-buttons {
            display: flex;
            gap: 8px;
        }
        
        .edit-btn {
            padding: 4px 8px;
            background-color: #ff9800;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .edit-btn:hover {
            background-color: #e68a00;
        }
        
        .delete-btn {
            padding: 4px 8px;
            background-color: #f44336;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .delete-btn:hover {
            background-color: #da190b;
        }
        
        /* 分页控件 */
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }
        
        .pagination button {
            padding: 8px 12px;
            margin: 0 4px;
            border: 1px solid #ddd;
            background-color: #fff;
            color: #333;
            cursor: pointer;
            border-radius: 4px;
        }
        
        .pagination button:hover:not(:disabled) {
            background-color: #f5f5f5;
        }
        
        .pagination button.active {
            background-color: #2196F3;
            color: white;
            border-color: #2196F3;
        }
        
        .pagination button:disabled {
            cursor: not-allowed;
            opacity: 0.5;
        }
        
        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
            justify-content: center;
            align-items: center;
        }
        
        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 90%;
            max-width: 600px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        
        .modal-header h2 {
            margin: 0;
            font-size: 20px;
            color: #333;
        }
        
        /* 表单样式 */
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #666;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }
        
        .form-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }
        
        .confirm-btn {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .confirm-btn:hover {
            background-color: #45a049;
        }
        
        .cancel-btn {
            padding: 8px 16px;
            background-color: #f1f1f1;
            color: #333;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .cancel-btn:hover {
            background-color: #e1e1e1;
        }
        
        /* 无数据提示 */
        .no-data {
            text-align: center;
            padding: 40px;
            color: #999;
        }
        
        /* 开关样式 */
        .switch {
            position: relative;
            display: inline-block;
            width: 40px;
            height: 20px;
        }
        
        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 20px;
        }
        
        .slider:before {
            position: absolute;
            content: "";
            height: 16px;
            width: 16px;
            left: 2px;
            bottom: 2px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        
        input:checked + .slider {
            background-color: #2196F3;
        }
        
        input:checked + .slider:before {
            transform: translateX(20px);
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="page-title"  style="font-size: 1.2em;">用户管理</h1>
        
        <div class="content-area">
            <!-- 搜索筛选区域 -->
            <div class="search-filter">
                <input type="text" id="userSearch" class="search-input" placeholder="搜索用户名、职业...">
                <select id="occupationFilter" class="filter-select">
                    <option value="">所有职业</option>
                    <option value="学生">学生</option>
                    <option value="教师">教师</option>
                    <option value="医生">医生</option>
                    <option value="程序员">程序员</option>
                    <option value="其他">其他</option>
                </select>
                <select id="ageRangeFilter" class="filter-select">
                    <option value="">所有年龄段</option>
                    <option value="0-18">0-18岁</option>
                    <option value="19-30">19-30岁</option>
                    <option value="31-50">31-50岁</option>
                    <option value="51+">51岁以上</option>
                </select>
                <button class="search-btn" onclick="searchUsers()">搜索</button>
                <button class="add-btn" onclick="openUserModal('add')">添加用户</button>
            </div>
            
            <!-- 用户列表表格 -->
            <table class="data-table" id="userTable">
                <thead>
                    <tr style="font-size: 0.8em;">
                        <th>用户ID</th>
                        <th>用户名</th>
                        <th>年龄</th>
                        <th>职业</th>
                        <th>月预算</th>
                        <th>流量需求</th>
                        <th>通话需求</th>
                        <th>国际漫游</th>
                        <th>增值服务</th>
                        <th>合约偏好</th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 表格数据将通过JavaScript动态生成 -->
                </tbody>
            </table>
            
            <!-- 分页控件 -->
            <div class="pagination" id="userPagination">
                <!-- 分页控件将通过JavaScript动态生成 -->
            </div>
        </div>
    </div>
    
    <!-- 用户编辑/添加模态框 -->
    <div id="userModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="userModalTitle">添加用户</h2>
            </div>
            
            <form id="userForm">
                <input type="hidden" id="userId">
                
                <div class="form-group">
                    <label for="userName">用户名</label>
                    <input type="text" id="userName" name="userName" placeholder="请输入用户名" required>
                </div>
                
                <div class="form-group">
                    <label for="userAge">年龄</label>
                    <input type="number" id="userAge" name="age" placeholder="请输入年龄" required>
                </div>
                
                <div class="form-group">
                    <label for="userOccupation">职业</label>
                    <input type="text" id="userOccupation" name="occupation" placeholder="请输入职业" required>
                </div>
                
                <div class="form-group">
                    <label for="userMonthlyBudget">月预算</label>
                    <input type="number" id="userMonthlyBudget" name="monthlyBudget" placeholder="请输入月预算" required>
                </div>
                
                <div class="form-group">
                    <label for="userNetDemand">流量需求</label>
                    <input type="number" id="userNetDemand" name="netDemand" placeholder="请输入流量需求(GB)" required>
                </div>
                
                <div class="form-group">
                    <label for="userCallDemand">通话需求</label>
                    <input type="number" id="userCallDemand" name="callDemand" placeholder="请输入通话需求(分钟)" required>
                </div>
                
                <div class="form-group">
                    <label for="userNeedIntlRoam">国际漫游需求</label>
                    <div>
                        <label class="switch">
                            <input type="checkbox" id="userNeedIntlRoam" name="needIntlRoam">
                            <span class="slider"></span>
                        </label>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="userNeedVas">增值服务需求</label>
                    <div>
                        <label class="switch">
                            <input type="checkbox" id="userNeedVas" name="needVas">
                            <span class="slider"></span>
                        </label>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="userPreferContract">合约偏好</label>
                    <select id="userPreferContract" name="preferContract" required>
                        <option value="">请选择合约偏好</option>
                        <option value="月租">月租</option>
                        <option value="季度">季度</option>
                        <option value="半年">半年</option>
                        <option value="一年">一年</option>
                        <option value="两年">两年</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="userExtraRemark">备注</label>
                    <textarea id="userExtraRemark" name="extraRemark" placeholder="请输入备注信息"></textarea>
                </div>
                
                <div class="form-buttons">
                    <button type="button" class="cancel-btn" onclick="closeUserModal()">取消</button>
                    <button type="submit" class="confirm-btn">确认</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 确认删除模态框 -->
    <div id="confirmDeleteModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>确认删除</h2>
            </div>
            
            <p id="deleteConfirmMessage">您确定要删除此项吗？此操作不可撤销。</p>
            
            <div class="form-buttons">
                <button type="button" class="cancel-btn" onclick="closeConfirmDeleteModal()">取消</button>
                <button type="button" class="delete-btn" onclick="confirmDelete()">确认删除</button>
            </div>
        </div>
    </div>
    
    <script>
        // 环境切换开关：'dev' 开发环境（调用本地http接口），'prod' 生产环境（调用/api接口）
        const ENV_MODE = 'prod'; // 修改此值切换环境
        
        // 当前编辑的数据ID
        let currentEditId = null;
        let mockUsers = []; // 用户数据，将从接口加载
        let currentPage = 1;
        const pageSize = 10;
        
        // 页面加载时初始化
        window.addEventListener('load', function() {
            loadUsers();
        });
        
        // 从服务器加载用户数据
        function loadUsers() {
            // 实际应用中应该发送请求到服务器获取数据
            // 这里使用TaocanController的listUser接口
            
            const apiUrl = ENV_MODE === 'dev' 
                ? 'http://localhost:8181/ai/taocan/listUser' 
                : '/api/taocan/listUser';
                
            fetch(apiUrl) // 使用TaocanController的listUser接口
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    mockUsers = data;
                    loadUserTable();
                })
                .catch(error => {
                    console.error('Error fetching users:', error);
                    
                    // 由于是模拟环境，当接口调用失败时，使用模拟数据
                    mockUsers = [
                        {id: 1, userName: '张三', age: 25, occupation: '程序员', monthlyBudget: 100, netDemand: 20, callDemand: 300, needIntlRoam: false, needVas: true, preferContract: '一年', extraRemark: '喜欢大流量套餐'},
                        {id: 2, userName: '李四', age: 30, occupation: '教师', monthlyBudget: 80, netDemand: 10, callDemand: 200, needIntlRoam: false, needVas: false, preferContract: '月租', extraRemark: '主要用于教学工作'},
                        {id: 3, userName: '王五', age: 40, occupation: '医生', monthlyBudget: 150, netDemand: 30, callDemand: 500, needIntlRoam: true, needVas: true, preferContract: '两年', extraRemark: '经常需要出差'},
                        {id: 4, userName: '赵六', age: 22, occupation: '学生', monthlyBudget: 50, netDemand: 15, callDemand: 100, needIntlRoam: false, needVas: true, preferContract: '月租', extraRemark: '校园生活'},
                        {id: 5, userName: '钱七', age: 35, occupation: '销售', monthlyBudget: 120, netDemand: 25, callDemand: 800, needIntlRoam: true, needVas: false, preferContract: '半年', extraRemark: '频繁出差'}
                    ];
                    
                    // 显示加载状态和模拟数据
                    loadUserTable();
                    console.log('使用模拟数据，因为API调用失败');
                });
        }
        
        // 加载用户表格数据
        function loadUserTable() {
            const tableBody = document.querySelector('#userTable tbody');
            tableBody.innerHTML = '';
            
            // 如果没有数据，显示无数据提示
            if (mockUsers.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="12" class="no-data">没有找到用户数据</td>';
                tableBody.appendChild(row);
                return;
            }
            
            // 计算分页数据
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = Math.min(startIndex + pageSize, mockUsers.length);
            const currentPageUsers = mockUsers.slice(startIndex, endIndex);
            
            currentPageUsers.forEach(user => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${user.id}</td>
                    <td>${user.userName}</td>
                    <td>${user.age}</td>
                    <td>${user.occupation}</td>
                    <td>¥${user.monthlyBudget.toFixed(2)}</td>
                    <td>${user.netDemand} </td>
                    <td>${user.callDemand} </td>
                    <td>${user.needIntlRoam ? '是' : '否'}</td>
                    <td>${user.needVas ? '是' : '否'}</td>
                    <td>${user.preferContract}</td>
                    <td>${user.extraRemark || '-'}</td>
                    <td class="action-buttons">
                        <button class="edit-btn" onclick="editUser(${user.id})">编辑</button>
                        <button class="delete-btn" onclick="confirmDeleteUser(${user.id}, '${user.userName}')">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
            
            // 加载分页控件
            loadPagination();
        }
        
        // 加载分页控件
        function loadPagination() {
            const pagination = document.getElementById('userPagination');
            pagination.innerHTML = '';
            
            const totalPages = Math.ceil(mockUsers.length / pageSize);
            
            // 上一页按钮
            const prevBtn = document.createElement('button');
            prevBtn.textContent = '上一页';
            prevBtn.disabled = currentPage === 1;
            prevBtn.addEventListener('click', () => {
                if (currentPage > 1) {
                    currentPage--;
                    loadUserTable();
                }
            });
            pagination.appendChild(prevBtn);
            
            // 页码按钮
            for (let i = 1; i <= totalPages; i++) {
                const pageBtn = document.createElement('button');
                pageBtn.textContent = i;
                if (i === currentPage) {
                    pageBtn.classList.add('active');
                }
                pageBtn.addEventListener('click', () => {
                    currentPage = i;
                    loadUserTable();
                });
                pagination.appendChild(pageBtn);
            }
            
            // 下一页按钮
            const nextBtn = document.createElement('button');
            nextBtn.textContent = '下一页';
            nextBtn.disabled = currentPage === totalPages;
            nextBtn.addEventListener('click', () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    loadUserTable();
                }
            });
            pagination.appendChild(nextBtn);
        }
        
        // 搜索用户
        function searchUsers() {
            const searchTerm = document.getElementById('userSearch').value.toLowerCase();
            const occupation = document.getElementById('occupationFilter').value;
            const ageRange = document.getElementById('ageRangeFilter').value;
            
            const tableBody = document.querySelector('#userTable tbody');
            tableBody.innerHTML = '';
            
            let filteredUsers = [...mockUsers];
            
            // 按搜索词筛选
            if (searchTerm) {
                filteredUsers = filteredUsers.filter(user => 
                    user.userName.toLowerCase().includes(searchTerm) ||
                    user.occupation.toLowerCase().includes(searchTerm) ||
                    user.extraRemark?.toLowerCase().includes(searchTerm)
                );
            }
            
            // 按职业筛选
            if (occupation) {
                filteredUsers = filteredUsers.filter(user => 
                    user.occupation === occupation
                );
            }
            
            // 按年龄段筛选
            if (ageRange) {
                const [min, max] = ageRange.split('-');
                if (max) {
                    filteredUsers = filteredUsers.filter(user => 
                        user.age >= parseInt(min) && user.age <= parseInt(max.replace('+', ''))
                    );
                } else {
                    filteredUsers = filteredUsers.filter(user => 
                        user.age >= parseInt(min.replace('+', ''))
                    );
                }
            }
            
            // 显示筛选结果
            if (filteredUsers.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="12" class="no-data">没有找到匹配的用户</td>';
                tableBody.appendChild(row);
            } else {
                filteredUsers.forEach(user => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${user.id}</td>
                        <td>${user.userName}</td>
                        <td>${user.age}</td>
                        <td>${user.occupation}</td>
                        <td>¥${user.monthlyBudget.toFixed(2)}</td>
                        <td>${user.netDemand} GB</td>
                        <td>${user.callDemand} 分钟</td>
                        <td>${user.needIntlRoam ? '是' : '否'}</td>
                        <td>${user.needVas ? '是' : '否'}</td>
                        <td>${user.preferContract}</td>
                        <td>${user.extraRemark || '-'}</td>
                        <td class="action-buttons">
                            <button class="edit-btn" onclick="editUser(${user.id})">编辑</button>
                            <button class="delete-btn" onclick="confirmDeleteUser(${user.id}, '${user.userName}')">删除</button>
                        </td>
                    `;
                    tableBody.appendChild(row);
                });
            }
        }
        
        // 打开用户模态框
        function openUserModal(mode, userId = null) {
            const modal = document.getElementById('userModal');
            const modalTitle = document.getElementById('userModalTitle');
            const userForm = document.getElementById('userForm');
            
            // 重置表单
            userForm.reset();
            
            // 设置模态框标题
            if (mode === 'add') {
                modalTitle.textContent = '添加用户';
                currentEditId = null;
            } else {
                modalTitle.textContent = '编辑用户';
                currentEditId = userId;
                
                // 填充表单数据
                const user = mockUsers.find(u => u.id === userId);
                if (user) {
                    document.getElementById('userId').value = user.id;
                    document.getElementById('userName').value = user.userName;
                    document.getElementById('userAge').value = user.age;
                    document.getElementById('userOccupation').value = user.occupation;
                    document.getElementById('userMonthlyBudget').value = user.monthlyBudget;
                    document.getElementById('userNetDemand').value = user.netDemand;
                    document.getElementById('userCallDemand').value = user.callDemand;
                    document.getElementById('userNeedIntlRoam').checked = user.needIntlRoam;
                    document.getElementById('userNeedVas').checked = user.needVas;
                    document.getElementById('userPreferContract').value = user.preferContract;
                    document.getElementById('userExtraRemark').value = user.extraRemark || '';
                }
            }
            
            // 显示模态框
            modal.style.display = 'flex';
        }
        
        // 关闭用户模态框
        function closeUserModal() {
            document.getElementById('userModal').style.display = 'none';
        }
        
        // 打开确认删除模态框
        function openConfirmDeleteModal(itemId, itemName, itemType) {
            const modal = document.getElementById('confirmDeleteModal');
            const confirmMessage = document.getElementById('deleteConfirmMessage');
            
            confirmMessage.textContent = `您确定要删除用户"${itemName}"吗？此操作不可撤销。`;
            currentEditId = itemId;
            
            modal.style.display = 'flex';
        }
        
        // 关闭确认删除模态框
        function closeConfirmDeleteModal() {
            document.getElementById('confirmDeleteModal').style.display = 'none';
        }
        
        // 确认删除
        function confirmDelete() {
            // 实际应用中应该发送请求到服务器删除数据
            const index = mockUsers.findIndex(user => user.id === currentEditId);
            if (index !== -1) {
                mockUsers.splice(index, 1);
                loadUserTable();
            }
            
            // 关闭模态框
            closeConfirmDeleteModal();
        }
        
        // 编辑用户
        function editUser(userId) {
            openUserModal('edit', userId);
        }
        
        // 确认删除用户
        function confirmDeleteUser(userId, userName) {
            openConfirmDeleteModal(userId, userName, 'user');
        }
        
        // 表单提交处理
        document.getElementById('userForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 收集表单数据
            const userId = document.getElementById('userId').value;
            const userName = document.getElementById('userName').value;
            const age = parseInt(document.getElementById('userAge').value);
            const occupation = document.getElementById('userOccupation').value;
            const monthlyBudget = parseFloat(document.getElementById('userMonthlyBudget').value);
            const netDemand = parseInt(document.getElementById('userNetDemand').value);
            const callDemand = parseInt(document.getElementById('userCallDemand').value);
            const needIntlRoam = document.getElementById('userNeedIntlRoam').checked;
            const needVas = document.getElementById('userNeedVas').checked;
            const preferContract = document.getElementById('userPreferContract').value;
            const extraRemark = document.getElementById('userExtraRemark').value;
            
            // 创建用户对象
            const userData = {
                id: userId ? parseInt(userId) : Date.now(), // 临时ID，实际应该由服务器生成
                userName,
                age,
                occupation,
                monthlyBudget,
                netDemand,
                callDemand,
                needIntlRoam,
                needVas,
                preferContract,
                extraRemark
            };
            
            // 实际应用中应该发送请求到服务器保存数据
            if (currentEditId) {
                // 编辑现有用户
                const index = mockUsers.findIndex(user => user.id === currentEditId);
                if (index !== -1) {
                    mockUsers[index] = userData;
                }
            } else {
                // 添加新用户
                mockUsers.push(userData);
            }
            
            // 更新表格
            loadUserTable();
            
            // 关闭模态框
            closeUserModal();
        });
        
        // 点击模态框外部关闭模态框
        window.addEventListener('click', function(event) {
            const modals = [
                document.getElementById('userModal'),
                document.getElementById('confirmDeleteModal')
            ];
            
            modals.forEach(modal => {
                if (event.target === modal) {
                    modal.style.display = 'none';
                }
            });
        });
    </script>
</body>
</html>